import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { message } from 'antd';
import router from 'umi/router';
import {
  queryDetailInfo,
  updateVipUser,
  saveVipUser,
} from './service';
import { fetchValidation } from '@/utils';

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: {};
  effects: {
    fetch: Effect;
    saveOrUpdate: Effect;
  };
  reducers: {
    save: Reducer;
    clear: Reducer;
  };
}

const initData = {
  dataInfo: {},
};

const Model: ModelType = {
  namespace: 'PostChargesSaveAndEdit',

  state: initData,

  effects: {
    * fetch({ payload }, { call, put }) {
      const response = yield call(queryDetailInfo, payload);
      const data = fetchValidation(response);
      if (data) {
        yield put({
          type: 'save',
          payload: response.body,
        });
      }
    },

    * saveOrUpdate({ payload }, { call, put }) {
      const response = yield call((payload.id ? updateVipUser : saveVipUser), payload);
      const data = fetchValidation(response);
      if (data) {
        message.success(payload.id ? '修改成功!' : '添加成功!');
        router.goBack();
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        dataInfo: action.payload,
      };
    },

    clear() {
      return ({
        initData: {
          dataInfo: {},
        },
      });
    },
  },
};

export default Model;
